import os
import re

from common.Tools import list_files, handle_patch_file
from common.ToolsExcel import create_excel, create_sheet, add_to_sheet

GOOGLE_PATCH_DIR = "/home/android/Documents/google_patch"
PLATFORM_VERSION = "6.0.1"
PLATFORM_VERSION_DETAIL = "android-6.0.1_r20"

PROJECT_PATH = "/home/android/Platform/6739O/android"

if __name__ == '__main__':
    file_list = list_files(GOOGLE_PATCH_DIR)
    file_list.sort()

    all_info = []

    all_count = 0
    patched_count = 0

    workbook = create_excel()
    sheet = create_sheet(workbook, 'patch_info', True)

    csv_info_line = "html" + ","
    csv_info_line = csv_info_line + "cve name" + ","
    csv_info_line = csv_info_line + "Level" + ","
    csv_info_line = csv_info_line + "patch identifier" + ","
    csv_info_line = csv_info_line + "base git path" + ","
    csv_info_line = csv_info_line + "patch path" + ","
    csv_info_line = csv_info_line + "patch result" + ","

    first_row = ['No', 'html', 'name', 'Level', 'patch identifier', 'base git path', 'patch path', 'patch result']
    add_to_sheet(sheet, first_row, 1)

    for file_ in file_list:
        type_name = os.path.splitext(file_)[1]
        if type_name == ".Identifier":
            print("rm file %s " % file_)
            os.remove(file_)
        elif type_name == ".html":
            with open(file_) as f:
                content = f.read()
                print("++++++++++++++++++++++++")
                print("from file %s" % file)
                matches = re.search(
                    r'later must address the following issues.</p>(.*?)<table class="table-style-one">(.*?)<h3',
                    content, re.M | re.S | re.DOTALL)
                # print(matches.group(0))
                items = re.search(r'<tbody>(.*?)</tbody>', matches.group(0), re.M | re.S | re.DOTALL)
                # print(items.group(0))
                matches = re.findall(r'<td>(.*?)</td>', items.group(0), re.M | re.S | re.DOTALL)
                # items = matches.groups()

                all_cve = []

                for item in matches:
                    if item.startswith("CVE"):
                        if "," in item:
                            names = item.split(",")
                            for name in names:
                                # print(name.strip())
                                all_cve.append(name.strip())
                        else:
                            # print(item.strip())
                            all_cve.append(item.strip())

                            # pattern = r'<td>' + item + '</td></tr>'
                            # cve_patch_names = re.findall(pattern, content, re.M | re.S | re.DOTALL)
                            # print(item, pattern)
                            # print(cve_patch_names)
                print(all_cve)

            file_line_list = []
            with open(file_) as f:
                file_line_list = f.readlines()

            for cve in all_cve:
                for i in range(len(file_line_list)):
                    line = file_line_list[i]
                    cve = cve[cve.find("CVE"):]
                    if cve in line:
                        temp = [file_line_list[i - 2],
                                file_line_list[i - 1],
                                file_line_list[i - 0],
                                file_line_list[i + 1],
                                file_line_list[i + 2],
                                file_line_list[i + 3],
                                file_line_list[i + 4]]
                        version_in = None
                        level_in = None
                        patch_name = None
                        for aaa in temp:
                            if PLATFORM_VERSION in aaa:
                                version_in = aaa.strip()
                            elif "Critical" in aaa or "High" in aaa:
                                level_in = aaa.strip()
                            elif "A-" in aaa:
                                patch_name = aaa.strip()

                            if level_in and version_in and patch_name:
                                all_count = all_count + 1
                                print("$$$$$$$$$$$$$$$$$ cve %s index %s" % (cve, all_count))
                                print(version_in)
                                print(level_in)
                                print(patch_name)

                                parent_dir = os.path.abspath(os.path.join(file_, ".."))

                                subdir_names = list_files(parent_dir)
                                for sub_name in subdir_names:
                                    # print("ssss", sub_name)
                                    # print("bbbbaa", patch_name.strip()[6: -5])
                                    if str(patch_name.strip()[6: -5]) in str(sub_name):
                                        # print("get patch name is ", sub_name)
                                        patch_apply_path = sub_name
                                        with open(sub_name) as f:
                                            all_lines = f.readlines()
                                            for xxx in all_lines:
                                                if PLATFORM_VERSION_DETAIL in xxx:
                                                    # print("patch git", xxx)
                                                    ccc = xxx.strip().split("/")
                                                    # print("ccc", ccc)
                                                    base_git = PROJECT_PATH
                                                    for q in range(2, len(ccc)):
                                                        base_git = os.path.join(base_git, ccc[q].strip())
                                                    for q in range(2, len(ccc)):
                                                        base_git = os.path.abspath(os.path.join(base_git, ".."))
                                                        repo_name = base_git[len(PROJECT_PATH):]
                                                        if os.path.isdir(base_git):
                                                            nnn = os.path.join(base_git, ".git")
                                                            if os.path.isdir(nnn):
                                                                # print("is git ", nnn)
                                                                patch_real_path = os.path.abspath(
                                                                    os.path.join(sub_name, "..", ".."))
                                                                dst_repo_name = base_git[len(PROJECT_PATH):]
                                                                # print("patch_real_path0", patch_real_path)
                                                                patch_real_path = os.path.join(patch_real_path,
                                                                                               xxx).strip()
                                                                # print("patch_real_path01", patch_real_path)

                                                                csv_info_line = file_ + ","
                                                                csv_info_line = csv_info_line + cve + ","
                                                                csv_info_line = csv_info_line + level_in + ","
                                                                csv_info_line = csv_info_line + patch_name + ","
                                                                csv_info_line = csv_info_line + base_git + ","
                                                                csv_info_line = csv_info_line + xxx.strip() + ","

                                                                try:
                                                                    handle_patch_file(base_git, patch_real_path,
                                                                                      repo_name, dst_repo_name)
                                                                except:
                                                                    print("patch %s failed", patch_real_path)
                                                                    csv_info_line = csv_info_line + "Fail" + ","
                                                                    csv_info_f.write(csv_info_line + os.linesep)
                                                                    csv_info_f.flush()
                                                                    break
                                                                commit_str = patch_real_path.split("/")
                                                                commit_str = cve + commit_str[len(commit_str) - 1]
                                                                execute_cmd = shell_path + " " + base_git + " " + patch_real_path + "bk" + " " + commit_str  # + " " + "false"
                                                                print("execute_cmd", execute_cmd)
                                                                print("base_git", base_git)
                                                                print("patch_real_path", patch_real_path + "bk")
                                                                print("commit_str", commit_str)
                                                                # if "android/frameworks" in base_git:
                                                                if not bool_commit:
                                                                    print("not commit patch path:%s" % (
                                                                        patch_real_path))
                                                                    patched_count = patched_count + 1
                                                                    csv_info_line = csv_info_line + "NotCommit" + ","
                                                                    csv_info_f.write(csv_info_line + os.linesep)
                                                                    csv_info_f.flush()
                                                                else:
                                                                    try:
                                                                        ret = subprocess.check_output(execute_cmd,
                                                                                                      shell=True)
                                                                        print(
                                                                                "patch success ret:%s patch path:%s" % (
                                                                            ret, patch_real_path))
                                                                        patched_count = patched_count + 1
                                                                        csv_info_line = csv_info_line + "Success" + ","
                                                                        csv_info_f.write(csv_info_line + os.linesep)
                                                                        csv_info_f.flush()
                                                                    except:
                                                                        print(
                                                                                "patch failed patch path:%s" % patch_real_path)
                                                                        csv_info_line = csv_info_line + "Fail" + ","
                                                                        csv_info_f.write(csv_info_line + os.linesep)
                                                                        csv_info_f.flush()
                                                                    break
                                                                    # else:
                                                                    #     print("not frameworks git %s " % base_git)
                                                                    #     break

                                                    break
                                print("**************")
                                break
